package dao

import (
	"TTMS/model"
	"TTMS/utils"
	"time"
)

// AddOrder 向数据库中添加订单
func AddOrder(order *model.Order) error {
	//写 sql 语句
	sqlStr := "insert into orders(id, create_time, total_count, total_amount, state, user_id, film_name, price, hall_id, schedule_id) values (?,?,?,?,?,?,?,?,?,?)"
	//执行
	_, err := utils.DB.Exec(sqlStr, order.OrderID, order.CreateTime, order.TotalCount, order.TotalAmount, order.State, order.UserID, order.FilmName, order.Price, order.HallID, order.ScheduleID)
	if err != nil {
		return err
	}
	return nil
}

// UpdateOrder 根据订单编号更新订单的状态
func UpdateOrder(orderID string, state int64) error {
	//写 sql 语句
	sqlStr := "update orders set state=? where id=?"
	//执行
	_, err := utils.DB.Exec(sqlStr, state, orderID)
	if err != nil {
		return err
	}
	return nil
}

// UpdateOrderWait 根据订单编号更新订单的状态
func UpdateOrderWait(orderID string, state int64) error {
	time.Sleep(30 * time.Second)
	//写 sql 语句
	sqlStr := "update orders set state=? where id=?"
	//执行
	_, err := utils.DB.Exec(sqlStr, state, orderID)
	if err != nil {
		return err
	}
	return nil
}

// GetOrder 获取订单
func GetOrder(orderID string) *model.Order {
	//写 sql 语句
	sqlStr := "select id, create_time, total_count, total_amount, state, user_id, film_name, price, hall_id, schedule_id from orders where id=?"
	//执行
	row := utils.DB.QueryRow(sqlStr, orderID)
	order := &model.Order{}
	row.Scan(&order.OrderID, &order.CreateTime, &order.TotalCount, &order.TotalAmount, &order.State, &order.UserID, &order.FilmName, &order.Price, &order.HallID, &order.ScheduleID)
	return order
}

// GetOrdersByUserID 根据用户ID获取订单
func GetOrdersByUserID(userID int64) ([]*model.Order, error) {
	//写 sql 语句
	sqlStr := "select id, create_time, total_count, total_amount, state, user_id, film_name, price, hall_id, schedule_id from orders where user_id=? order by create_time desc"
	//执行
	rows, err := utils.DB.Query(sqlStr, userID)
	if err != nil {
		return nil, err
	}
	var orders []*model.Order
	for rows.Next() {
		order := &model.Order{}
		rows.Scan(&order.OrderID, &order.CreateTime, &order.TotalCount, &order.TotalAmount, &order.State, &order.UserID, &order.FilmName, &order.Price, &order.HallID, &order.ScheduleID)
		order.Seats, _ = GetSeatsByOrderID(order.OrderID)
		orders = append(orders, order)
	}
	return orders, nil
}
